package com.agileai.wm.service.weekexam;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

import com.agileai.domain.DataRow;
import com.agileai.hotweb.controller.core.BaseHandler;
import com.agileai.hotweb.domain.core.User;
import com.agileai.hotweb.ws.BaseRestService;
import com.agileai.util.DateUtil;
import com.agileai.util.StringUtil;
import com.agileai.wm.cxmodule.WmDayworkManage;
import com.agileai.wm.cxmodule.WmWeekManage;

public class WeekWorkExamImpl extends BaseRestService implements WeekWorkExam {
	private String UNDEFINED = "undefined";
	private static String State = "CONFIRMED";
	private static String ENTRYSTATE = "1";
	
	@Override
	public String retrieveWeekExamUserInfos(String grpId) {
		String responseText = BaseHandler.FAIL;
		try {
			WmWeekManage wmWeekManage = this.lookupService(WmWeekManage.class);
			
			if(UNDEFINED.equals(grpId)){
				User user =  (User)this.getUser();
				String userFavor = (String)user.getProperties().get("WM_USER_FAVORITES");
				if(!StringUtil.isNullOrEmpty(userFavor)){
					JSONObject userFavJson = new JSONObject(userFavor);
					if(!userFavJson.isNull("weekProjectId")){
						grpId = userFavJson.getString("weekProjectId");
					}else{
						List<DataRow> projectRecords = wmWeekManage.initGroupRecords(user.getUserId());
						if(projectRecords.size() > 0){
							grpId = projectRecords.get(0).getString("GRP_ID");
						}
					}
				}else{
					List<DataRow> projectRecords = wmWeekManage.initGroupRecords(user.getUserId());
					if(projectRecords.size() > 0){
						grpId = projectRecords.get(0).getString("GRP_ID");
					}
					
				}
			}
			List<DataRow> userRecords =  wmWeekManage.findWeekExaminationUserInfos(grpId);
			
			JSONObject jsonObject = new JSONObject();
			JSONArray userInfosArray = new JSONArray();
			JSONArray userCodesArray = new JSONArray();
			if(userRecords.size() > 0){
				for(int i=0;i<userRecords.size();i++){
					DataRow row = userRecords.get(i);
					JSONObject userInfoJson = new JSONObject();
					userInfoJson.put("userId", row.stringValue("USER_ID"));
					userInfoJson.put("userName",row.stringValue("USER_NAME"));
					userInfoJson.put("userCode", row.stringValue("USER_CODE"));
					userInfosArray.put(userInfoJson);
					userCodesArray.put(row.stringValue("USER_CODE"));
				}
			}else{
				JSONObject userInfoJson = new JSONObject();
				userInfoJson.put("userName","无记录");
				userInfosArray.put(userInfoJson);
				userCodesArray.put("无记录");
			}
			
			jsonObject.put("userInfos", userInfosArray);
			jsonObject.put("userCodes", userCodesArray);
			jsonObject.put("grpId", grpId);
			responseText = jsonObject.toString();
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(),e);
		}
		return responseText;
	}

	@Override
	public String findProjectInfos() {
		String responseText = BaseHandler.FAIL;
		try {
			User user = (User)this.getUser();
			String userId = user.getUserId();
			
			String wmUserFavorites = (String) user.getProperties().get("WM_USER_FAVORITES");
			String wmUserProjectId = "";
			if(!StringUtil.isNullOrEmpty(wmUserFavorites)){
				JSONObject wmUserFavJson = new JSONObject(wmUserFavorites);
				if(!wmUserFavJson.isNull("weekProjectId")){
					wmUserProjectId = wmUserFavJson.getString("weekProjectId");
				}
			}
			WmWeekManage wmWeekManage = this.lookupService(WmWeekManage.class);
			List<DataRow> projectRecords = wmWeekManage.initGroupRecords(userId);
			List<String> projectGrps = new ArrayList<String>();
			for(int i=0;i<projectRecords.size();i++){
				String id = projectRecords.get(i).getString("GRP_ID");
				projectGrps.add(id);
			}
	
			if(!(projectGrps.contains(wmUserProjectId)) && projectRecords.size() > 0){
				wmUserProjectId =  projectRecords.get(0).getString("GRP_ID");
			}
			
			JSONObject jsonObject = new JSONObject();
			JSONArray projectArray = new JSONArray();
			for(int i=0;i<projectRecords.size();i++){
				DataRow row = projectRecords.get(i);
				JSONObject projectJson = new JSONObject();
				projectJson.put("projectId", row.stringValue("GRP_ID"));
				projectJson.put("projectName",row.stringValue("GRP_NAME"));
				projectArray.put(projectJson);
			}
			jsonObject.put("projectInfos", projectArray);
			jsonObject.put("projectId", wmUserProjectId);
			
			responseText = jsonObject.toString();
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(),e);
		}
		return responseText;
	}

	@Override
	public String retrieveCurSeleWeekInfos(String weekTimeId, String userId,
			String grpId) {
		String responseText = BaseHandler.FAIL;
		try {
			User user = (User)this.getUser();
			if(UNDEFINED.equals(userId)){
				userId = user.getUserId();
			}
			WmWeekManage wmWeekManage = this.lookupService(WmWeekManage.class);
			String grpName = "";
			if(null != grpId){
				DataRow grpRow = wmWeekManage.queryGroupRecord(grpId);
				grpName = grpRow.stringValue("GRP_NAME");
			}
			
			DataRow row1 = wmWeekManage.getCurrentWeekRow(weekTimeId);
			String currentDate = DateUtil.getDateByType(DateUtil.YYMMDD_HORIZONTAL,new Date());
			String currentWeekId = "";
			String startTime = "";
			String endTime = "";
			if(row1 != null && row1.size() > 0){
				currentWeekId = row1.stringValue("WT_ID");
				startTime = row1.stringValue("WT_BEGIN");
				endTime = row1.stringValue("WT_END");
			}else{
				row1 = wmWeekManage.getCurrentWeekTimeId(currentDate);
				currentWeekId = row1.stringValue("WT_ID");
				startTime = row1.stringValue("WT_BEGIN");
				endTime = row1.stringValue("WT_END");
			}
			DataRow weekManageRow = wmWeekManage.getMasterWeekWorkRecord(userId,currentWeekId);
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("startTime", startTime);
			jsonObject.put("time", startTime);
			jsonObject.put("endTime", endTime);
			jsonObject.put("weekTimeId", currentWeekId);
			
			jsonObject.put("grpName", grpName);
			if(weekManageRow != null){
				jsonObject.put("wwDay", weekManageRow.stringValue("WW_DAY"));
				jsonObject.put("weekWorkId", weekManageRow.stringValue("WW_ID"));
				jsonObject.put("state", weekManageRow.stringValue("WW_STATE"));
				jsonObject.put("stateName", weekManageRow.stringValue("CODE_NAME"));
				String completion =  weekManageRow.stringValue("WW_COMPLETION");
				if("0".equals(completion)){
					jsonObject.put("completion","");
				}else{
					jsonObject.put("completion",completion);
				}
			}else{
				jsonObject.put("wwDay", "0");
				jsonObject.put("weekWorkId","无记录");
				jsonObject.put("stateName", "空");
			}
			
			List<DataRow> weekWorkRecords = wmWeekManage.getWeekWorkRecord(userId,currentWeekId);
			JSONArray wmWeekArray = new JSONArray();
			if(weekWorkRecords.size() != 0){
				for(int i=0;i<weekWorkRecords.size();i++){
					DataRow row = weekWorkRecords.get(i);
					JSONObject wmWeekJson = new JSONObject();
					wmWeekJson.put("describe", row.stringValue("ENTRY_DESCRIBE"));
					wmWeekJson.put("planday", row.stringValue("ENTRY_PLAN"));
					wmWeekArray.put(wmWeekJson);
				}
			}else{
				JSONObject wmWeekJson = new JSONObject();
				wmWeekJson.put("describe", "无记录");
				wmWeekJson.put("planday", "0");
				wmWeekArray.put(wmWeekJson);
			}
			
			List<DataRow> prepareWeekRecords = wmWeekManage.getWeekPrepareRecord(userId,currentWeekId);
			JSONArray prepareWeekArray = new JSONArray();
			if(prepareWeekRecords.size() != 0){
				for(int i=0;i<prepareWeekRecords.size();i++){
					DataRow row = prepareWeekRecords.get(i);
					JSONObject prepareWeekJson = new JSONObject();
					prepareWeekJson.put("predesc", row.stringValue("PRE_DESCRIBE"));
					prepareWeekJson.put("preplanday", row.stringValue("PRE_LOAD"));
					prepareWeekArray.put(prepareWeekJson);
				}
			}else{
				JSONObject prepareWeekJson = new JSONObject();
				prepareWeekJson.put("predesc", "无记录");
				prepareWeekJson.put("preplanday", "0");
				prepareWeekArray.put(prepareWeekJson);
			}
			jsonObject.put("plan", wmWeekArray);
			jsonObject.put("follow", prepareWeekArray);
			responseText = jsonObject.toString();
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(),e);
		}
		return responseText;
	}

	@Override
	public String submitCurWeekWork(String weekWorkId) {
		String responseText = BaseHandler.FAIL;
		try {
			WmWeekManage wmWeekManage = this.lookupService(WmWeekManage.class);
			if(!UNDEFINED.equals(weekWorkId)){
				wmWeekManage.doSubmitWeekWork(weekWorkId,State);
				
		    	wmWeekManage.doSubmitEntryWeekWork(weekWorkId,ENTRYSTATE);
				responseText = BaseHandler.SUCCESS;
			}
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(),e);
		}
		return responseText;
	}

	@Override
	public String showSubmitBtn(String grpId,String userCode) {
		String responseText = BaseHandler.FAIL;
		
		try {
			String selectUserCode = userCode;
			User user = (User)this.getUser();
			String curUserCode = user.getUserCode();
			String userId = user.getUserId();
			
			JSONObject jsonObject = new JSONObject();
			if(!curUserCode.equals(selectUserCode)){
				WmWeekManage wmWeekManage = this.lookupService(WmWeekManage.class);
				if(!UNDEFINED.equals(grpId)){
					DataRow grpRow = wmWeekManage.queryGroupRecord(grpId);
					grpId = grpRow.stringValue("GRP_ID");
				}
				List<DataRow> empJobRecords = wmWeekManage.quertUserEmpJobRecords(userId,grpId);
				if(empJobRecords.size() > 0){
					for(int i=0;i<empJobRecords.size();i++){
						DataRow row = empJobRecords.get(i);
						String empJob = row.stringValue("EMP_JOB");
						if("Master".equals(empJob)){
							jsonObject.put("showSubmitBtn", true);
						}else if("Auditer".equals(empJob)){
							jsonObject.put("showSubmitBtn", true);
						}else{
							jsonObject.put("showSubmitBtn", false);
						}
					}
				}else{
					jsonObject.put("showSubmitBtn", false);
				}
			}else{
				jsonObject.put("showSubmitBtn",false);
			}
			
			responseText = jsonObject.toString();
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(),e);
		}
		return responseText;
	}

	@Override
	public String retrieveWeekworkInfos(String weekWorkId, String userId,String grpId) {
		String responseText = BaseHandler.FAIL;
		try {
			User user = (User)this.getUser();
			if(null == userId){
				userId = user.getUserId();
			}
			WmWeekManage wmWeekManage = this.lookupService(WmWeekManage.class);
			DataRow grpRow = wmWeekManage.queryGroupRecord(grpId);
			String grpName = grpRow.stringValue("GRP_NAME");
			
			DataRow weekManageRow = wmWeekManage.getCurrentSelectWeekInfo(weekWorkId);
			String weekTimeId = weekManageRow.stringValue("WT_ID");
//			DataRow row1 = wmWeekManage.getNextWeekRow(weekTimeId);
			DataRow wmWeekRow = wmWeekManage.getCurrentWeekRow(weekTimeId);
			
			String startTime = wmWeekRow.stringValue("WT_BEGIN");
			String endTime = wmWeekRow.stringValue("WT_END");
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("startTime", startTime);
			jsonObject.put("time", startTime);
			jsonObject.put("endTime", endTime);
			jsonObject.put("weekTimeId", weekTimeId);
			
			jsonObject.put("grpName", grpName);
			
			jsonObject.put("wwDay", weekManageRow.stringValue("WW_DAY"));
			jsonObject.put("weekWorkId", weekManageRow.stringValue("WW_ID"));
			jsonObject.put("state", weekManageRow.stringValue("WW_STATE"));
			jsonObject.put("stateName", weekManageRow.stringValue("CODE_NAME"));
			String completion =  weekManageRow.stringValue("WW_COMPLETION");
			if("0".equals(completion)){
				jsonObject.put("completion","");
			}else{
				jsonObject.put("completion",completion);
			}
			
			List<DataRow> followWeekRecords = wmWeekManage.getWeekWorkRecord(userId,weekTimeId);
			JSONArray followWeekArray = new JSONArray();
			if(followWeekRecords.size() != 0){
				for(int i=0;i<followWeekRecords.size();i++){
					DataRow row = followWeekRecords.get(i);
					JSONObject followWeekJson = new JSONObject();
					followWeekJson.put("describe", row.stringValue("ENTRY_DESCRIBE"));
					followWeekJson.put("planday", row.stringValue("ENTRY_PLAN"));
					followWeekArray.put(followWeekJson);
				}
			}else{
				JSONObject followWeekJson = new JSONObject();
				followWeekJson.put("describe", "无记录");
				followWeekJson.put("planday", "0");
				followWeekArray.put(followWeekJson);
			}
			
			List<DataRow> prepareWeekRecords = wmWeekManage.getWeekPrepareRecord(userId,weekTimeId);
			JSONArray prepareWeekArray = new JSONArray();
			if(prepareWeekRecords.size() != 0){
				for(int i=0;i<prepareWeekRecords.size();i++){
					DataRow row = prepareWeekRecords.get(i);
					JSONObject prepareWeekJson = new JSONObject();
					prepareWeekJson.put("predesc", row.stringValue("PRE_DESCRIBE"));
					prepareWeekJson.put("preplanday", row.stringValue("PRE_LOAD"));
					prepareWeekArray.put(prepareWeekJson);
				}
			}else{
				JSONObject prepareWeekJson = new JSONObject();
				prepareWeekJson.put("predesc", "无记录");
				prepareWeekJson.put("preplanday", "0");
				prepareWeekArray.put(prepareWeekJson);
			}
			jsonObject.put("plan", followWeekArray);
			jsonObject.put("follow", prepareWeekArray);
			responseText = jsonObject.toString();
		} catch (Exception e) {
			log.error(e.getLocalizedMessage(),e);
		}
		return responseText;
	}

	@Override
	public String syncUserProjectId(String grpId) {
		String responseText = BaseHandler.FAIL;
		try {
			User user = (User)this.getUser();
			String userId = user.getUserId();
			String wnUserFav = (String) user.getProperties().get("WM_USER_FAVORITES");
			JSONObject jsonObject = new JSONObject();
			if(!StringUtil.isNullOrEmpty(wnUserFav)){
				jsonObject = new JSONObject(wnUserFav);
			}
			jsonObject.put("weekProjectId", grpId);
			wnUserFav = jsonObject.toString();
			WmDayworkManage wmDayworkManage = this.lookupService(WmDayworkManage.class);
			wmDayworkManage.syncUserFavorites(userId,wnUserFav);
			user.getProperties().put("WM_USER_FAVORITES",wnUserFav);
			wnUserFav = (String) user.getProperties().get("WM_USER_FAVORITES");
		} catch (JSONException e) {
			e.printStackTrace();
		}
		responseText = BaseHandler.SUCCESS;
		return responseText;
	}

}
